var WishUtil = require('../../weixin/wishUtil');
var Wish = WishUtil.Wish;
var UserWish = WishUtil.UserWish;
var WISH_STATUS = WishUtil.WISH_STATUS;
var WISH_TYPE = WishUtil.WISH_TYPE;

var wishPopulate = 'desc minSupport maxDays';

function getWishListFunc(query, page, size, callback) {
    size = size ? size : 20;
    page = page ? page : 1;
    var index = (page - 1) * size;
    Wish.find(query).sort({_id: -1}).skip(index).limit(size).exec(function (err, result) {
        if (!err && result != null) {
            Wish.count(query).exec(function (err2, count) {
                var data = {
                    data: result,
                    count: count
                };
                callback(err, data);
            });
        } else {
            callback(err, result);
        }
    });
}

function getUserWishListFunc(query, page, size, callback) {
    size = size ? size : 20;
    page = page ? page : 1;
    var index = (page - 1) * size;
    UserWish.find(query).sort({_id: -1}).skip(index).limit(size).populate('wish', wishPopulate).exec(function (err, result) {
        if (!err && result != null) {
            var lenn = result.length;
            for (var i = 0; i < lenn; ++i) {
                WishUtil.addUserWishDetail(result[i], function () {});
            }
            UserWish.count(query).exec(function (err2, count) {
                var data = {
                    data: result,
                    count: count
                };
                callback(err, data);
            });
        } else {
            callback(err, result);
        }

    })
}

function deleteWishFunc(query, callback) {
    Wish.remove(query).exec(callback);
}

exports.getBackofficeWishListService = function (body, page, size, callback) {
    if (body.desc)
        body.desc = {"$regex": body.desc};
    getWishListFunc(body, page, size, callback);
};
exports.getBackofficeUserWishListService = function (body, page, size, callback) {
    if (!body.desc)
        getUserWishListFunc(body, page, size, callback);
    else {
        WishUtil.getWishFunc({desc: {"$regex": body.desc}}, function (err, result) {
            delete body.desc;
            body.wish = result._id;
            getUserWishListFunc(body, page, size, callback);
        });
    }
};

exports.createWishService = function (body, callback) {
    var w = new Wish();
    for (var k in body)
        w[k] = body[k];
    w.save(callback);
};

exports.updateWishService = function (wishId, updateObj, callback) {
    WishUtil.updateWishFunc({_id: wishId}, updateObj, callback);
};
exports.updateUserWishService = function (wishId, updateObj, callback) {
    WishUtil.updateUserWishFunc({_id: wishId}, updateObj, callback);
};

exports.deleteWishService = function (delObj, callback) {
    deleteWishFunc({_id: delObj}, callback);
};
